#!/usr/bin/perl
use FindBin;
use lib "$FindBin::Bin/lib";
use lib "$FindBin::Bin/lib/perl-lib/lib/perl5";

use strict;
use IO::File;
use Getopt::Long;
use SqlplusExec;
use AutoExecUtils;

sub usage {
    my $pname = $FindBin::Script;

    print("$pname --ORACLE_USER <ORACLE_USER> --ORACLE_SID <ORACLE_SID>\n");
    exit(1);
}

sub main {
    my $opts = {};
    GetOptions(
        $opts, qw{
            ORACLE_USER=s
            ORACLE_SID=s
            SQL=s
            verbose=i
        }
    );

    my $hasOptErr   = 0;
    my $ORACLE_USER = $opts->{ORACLE_USER};
    my $ORACLE_SID  = $opts->{ORACLE_SID};
    my $sqlTxt      = $opts->{SQL};
    my $verbose     = $opts->{verbose};

    if ( not defined($ORACLE_USER) or $ORACLE_USER eq '' ) {
        $hasOptErr = 1;
        print("ERROR: Must defined ORACLE_USER by option --ORACLE_USER.\n");
    }
    if ( $hasOptErr == 1 ) {
        usage();
    }

    my $hasError = 0;

    $sqlTxt =~ s/^\s*|\s*$//sg;
    $sqlTxt =~ s/\\n/\n/sg;
    $sqlTxt = $sqlTxt . "\n";

    my $sqlplus = SqlplusExec->new( osUser => $ORACLE_USER, sid => $ORACLE_SID );

    my $exitCode = $sqlplus->do(
        sql     => $sqlTxt,
        verbose => $verbose
    );

    if ( $exitCode != 0 ) {
        $hasError = 1;
        print("ERROR: Errors occur while executing sql.\n");
    }

    if ( $hasError == 0 ) {
        print("FINE: Execute sql scripts success.\n");
    }
    return $hasError;
}

exit( main() );
